package com.xiaoq.coms.util;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class HexUtil {
	public static class UnHexException extends Exception {
		private static final long serialVersionUID = -8276859381585168238L;

		public UnHexException() {
			super();
		}

		public UnHexException(String msg) {
			super(msg);
		}

		public UnHexException(Throwable cause) {
			super(cause);
		}

		public UnHexException(String msg, Throwable cause) {
			super(msg, cause);
		}
	}

	public static void main(String[] argv) throws Exception {
		String hexStr = HexUtil.hex("hello".getBytes("UTF-8"));
		System.out.println(hexStr);
		hexStr = HexUtil.hexUpperCase("hello".getBytes("UTF-8"));
		System.out.println(hexStr);
		try {
			byte[] b = HexUtil.unHex(hexStr);
			System.out.println(new String(b, "UTF-8"));
			b = HexUtil.unHex(hexStr.toUpperCase());
			System.out.println(new String(b, "UTF-8"));
		} catch (UnHexException e) {
			e.printStackTrace();
		}
	}

	public static String hex(byte[] b) {
		if (b == null || b.length == 0) {
			return "";
		}
		return Hex.encodeHexString(b);
	}

	public static String hexUpperCase(byte[] b) {
		if (b == null || b.length == 0) {
			return "";
		}
		return Hex.encodeHexString(b).toUpperCase();
	}

	public static byte[] unHex(String s) throws UnHexException {
		if (s == null || s.trim().length() == 0) {
			return null;
		}
		try {
			return Hex.decodeHex(s.toCharArray());
		} catch (DecoderException e) {
			throw new UnHexException(e);
		}
	}

}